package com.byt.framlib.basemvp.network;

import com.byt.framlib.basemvp.ApiConfig;
import com.byt.framlib.commonutils.LogUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpUtil {

    private OkHttpClient okHttpClient;
    private static OkHttpUtil instance = null;

    public static OkHttpUtil getInstance() {
        if (instance == null) {
            instance = new OkHttpUtil();
        }
        return instance;
    }

    private OkHttpUtil() {
        OkHttpClient.Builder mbuild = new OkHttpClient.Builder()
                .addInterceptor(getHttpLoggingInterceptor())                            //添加请求协议头
                .connectTimeout(ApiConfig.Host.DEFAULT_TIME_OUT, TimeUnit.SECONDS)      //设置连接超时
                .readTimeout(ApiConfig.Host.DEFAULT_TIME_READ, TimeUnit.SECONDS)        //设置读超时
                .writeTimeout(ApiConfig.Host.DEFAULT_TIME_WRITE, TimeUnit.SECONDS)      //设置写超时
                .retryOnConnectionFailure(true)                                         //是否自动重连
                .connectionPool(new ConnectionPool());                                   //链接线程池
        okHttpClient = mbuild.build();//构建OkHttpClient对象
    }

    /**
     * 普通POST方式请求 提交表单
     */
    public void postBody(String url, RequestBody body, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 普通get方式请求 提交表单
     */
    public void getBody(String url, Map<String,Object> map, Callback callback) {
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            urlBuilder.addQueryParameter(entry.getKey(), entry.getValue() + "");
        }
        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 日志输出
     * 自行判定是否添加
     *
     * @return
     */
    private HttpLoggingInterceptor getHttpLoggingInterceptor() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> LogUtils.loge(message));
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }
}